package com.tz.service.impl;

import com.tz.dao.IAccountDao;
import com.tz.entity.Account;
import com.tz.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.List;

/**
 * Created by yejf on 2017/1/10.
 */
@Service
public class AccountServiceImpl implements IAccountService {

    @Autowired
    private IAccountDao accountDao;

    public void setAccountDao(IAccountDao accountDao) {
        this.accountDao = accountDao;
    }

    @Override
    public void save(Account account) {
        accountDao.save(account);
    }

    @Override
    public void update(Account account) {
        accountDao.update(account);
    }

    @Override
    public Account get(Long id) {
        return accountDao.find(id);
    }

    @Override
    public List<Account> list() {
        return accountDao.findAll();
    }

    @Override
    public boolean checkNo(String no) {
        //直接判断
        return accountDao.findByNo(no) == null;
    }

    @Override
    @Transactional //这里开启了事务后，dao中的方法就会自动获取这里的事务，而不是全新的事务
    public String transfer(String from, String to, double money) {
        //判断
        Account fromAccount = accountDao.findByNo(from);
        //
        if(null == fromAccount) {
            return "源帐户不存在: "+from;
        }
        //
        Account toAccount = accountDao.findByNo(to);
        //
        if(null == toAccount) {
            return "目标帐户不存在: "+to;
        }
        //
        if(fromAccount.getBalance() < money) {
            return "源帐户的余额不足: "+fromAccount.getBalance();
        }
        //可以转帐了
        fromAccount.setBalance(fromAccount.getBalance() - money);
        accountDao.update(fromAccount);
        System.out.println("源帐户转出成功...");

        //模拟一个随机异常，以证明出现异常后，前面的会回滚
        randomException();

        toAccount.setBalance(toAccount.getBalance() + money);
        accountDao.update(toAccount);
        System.out.println("目标帐户转入成功...");
        //
        return "从帐户["+from+"]转帐到帐户["+to+"]成功，转帐金额："+money;
    }

    /**
     * 随机异常方法
     */
    private void randomException() {
        int second = Calendar.getInstance().get(Calendar.SECOND);
        if (second % 2 == 1) {
            throw new RuntimeException("自定义异常");
        }
    }

}
